import { ListRes, fetchList } from "@/apis/home";
import { Image, InfiniteScroll, List } from "antd-mobile";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";


// 父组件传参
type Props = {
  channelId: string
}

const HomeList = (props: Props) => {
  const { channelId } = props // 前台传过来的参数
  const [listRes, setListRes] = useState<ListRes>({
    reslutes: [],
    pre_timestamp: '' + new Date().getTime()
  })
  useEffect(() => {
    const getList = async () => {
      try {
        const res = await fetchList({
          channel_id: channelId,
          timestamp: '' + new Date().getTime()
        })
        setListRes({
          reslutes: res.data.data.reslutes,
          pre_timestamp: res.data.data.time
        })
      } catch (error) {
        throw new Error('报错', error)
      }
    }
    getList()
  }), [channelId] // 当传参发生变化的时候 再次请求接口

  // 加载下一页的函数
  const loadMore = async () => {
    try {
      const res = await fetchList({
        channel_id: channelId,
        timestamp: listRes.pre_timestamp
      })
      // 拼接新老数组
      setListRes({
        reslutes: [...listRes.reslutes, ...res.data.data.reslutes],
        pre_timestamp: res.data.data.time
      })
      // 停止加载
      if (res.data.data.reslutes.length === 0) {
        setHasMore(false)
      }
    } catch (error) {
      throw new Error('报错', error)
    }
  }
  // 开关 标记当前是否还有新数据
  const [hasMore, setHasMore] = useState(true)
// 跳转
const navigate = useNavigate()
const getDetails = (id:string) => {
  navigate(`/details?id=${id}`)
}


  return (
    <>
      <List>
        {listRes.map(item => (
          <List.Item key={item.id} onClick={getDetails(item.id)} prefix={
            <Image src="item.name" style={{ borderRadius: 20 }} fit="cover" width={40} height={40} />
          } description={item.name}>
            {item.name}
          </List.Item>
        ))}
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10} />
    </>
  )
}

export default HomeList